package com.cyj.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyj.comment.dto.ScrollResult;
import com.cyj.comment.dto.UserDTO;
import com.cyj.comment.entity.Blog;
import com.cyj.comment.entity.Follow;
import com.cyj.comment.entity.User;
import com.cyj.comment.mapper.BlogMapper;
import com.cyj.comment.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.comment.service.FollowService;
import com.cyj.comment.service.UserService;
import com.cyj.comment.utils.Result;
import com.cyj.comment.utils.SystemConstants;
import com.cyj.comment.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.cyj.comment.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.cyj.comment.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chixiaowai
 * @since 2023-04-04
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private FollowService followService;

    /**
     * 查询热门博客
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查询博客详情
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("博客不存在");
        }
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 点赞博客
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        String blogLikedKey = BLOG_LIKED_KEY + id;
        //判断当前用户是否已点赞
        Double score = stringRedisTemplate.opsForZSet().score(blogLikedKey, userId.toString());
        if (score == null){
            //未点赞，可以点赞
            //数据库点赞数+1
            boolean flag = update().setSql("liked = liked + 1").eq("id", id).update();
            if (flag){
                //保存用户到Redis的zset集合中
//                stringRedisTemplate.opsForSet().add(blogLikedKey, userId.toString());
                stringRedisTemplate.opsForZSet().add(blogLikedKey, userId.toString(), System.currentTimeMillis());
            }
        }else {
            //已点赞，取消点赞
            //数据库点赞数-1
            boolean flag = update().setSql("liked = liked - 1").eq("id", id).update();
            //将用户从Redis的zset集合中移除
            if (flag){
                stringRedisTemplate.opsForZSet().remove(blogLikedKey, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String blogLikeKey = BLOG_LIKED_KEY + id;
        //查询top5点赞用户
        Set<String> likeUserSet = stringRedisTemplate.opsForZSet().range(blogLikeKey, 0, 4);
        if (likeUserSet == null || likeUserSet.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //解析其中的用户id
        List<Long> ids = likeUserSet.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        //根据用户id查询用户
        List<UserDTO> userDTOList = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr +")").list()
                .stream()
                .map(user ->
                        BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //返回用户列表
        return Result.ok(userDTOList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //保存探店博文
        boolean success = save(blog);
        if (!success){
            return Result.fail("发布博客失败");
        }
        //查询博客作者的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //推送博客到所有粉丝
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    /**
     * 关注推送
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户的收件箱
        Long userId = UserHolder.getUser().getId();
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if (typedTuples == null){
            return Result.ok();
        }
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取blogId
            //解析数据：blogId、minTime、offset
            String idStr = typedTuple.getValue();
            blogIds.add(Long.valueOf(idStr));
            long time = typedTuple.getScore().longValue();
            if (time == minTime){
                os++;
            }else{
                //获取分数（时间戳）
                minTime = time;
                os = 1;
            }
        }
        //根据id查询blog
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogList = query().in("id", blogIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogList) {
            //查询blog有关的用户
            queryBlogUser(blog);
            //查询blog是否被点赞
            isBlogLiked(blog);
        }

        //封装并返回
        ScrollResult result = new ScrollResult();
        result.setList(blogList);
        result.setOffset(os);
        result.setMinTime(minTime);
        return Result.ok(result);
    }

    /**
     * 查询博客所属用户并将属性进行赋值
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 判断当前用户是否已点赞
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        // 2.判断当前登录用户是否已经点赞
        String blogLikedKey = BLOG_LIKED_KEY + blog.getId();
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(blogLikedKey, userId.toString());
//        blog.setIsLike(isMember);
        Double score = stringRedisTemplate.opsForZSet().score(blogLikedKey, userId.toString());
        blog.setIsLike(score != null);
    }
}
